import { reactive, toRefs, onUnmounted, onMounted } from 'vue';
import IWebsocket from './chatWS'
import pinia from '@/store/index';
import { Chat } from '@/store/chat';
const chat = Chat(pinia);
import { storeToRefs } from 'pinia';
const { autoreply, autoreplytext } = storeToRefs(chat);


const state_data: any = reactive({
  quickPhrasesList: '',
  timer: '',
  sendObj: {},
  autoSendObj: {},
});

const usechatHooks = (state?: any) => {
  // 解析消息体
  const decodeContent = (data: any, name: string) => {
    let MessageOutputeItem = state.root.lookupType(name)
    const buffer1 = new Uint8Array(data);
    const decodedMessage2 = MessageOutputeItem.decode(buffer1);

    return MessageOutputeItem.toObject(decodedMessage2);
  }

  const encodeInput = (type: any, request_id: any, data: any) => {
    state_data.Input = state.root.lookupType('Input');
    // Build payload object
    const payload = {
      type: type,
      requestid: request_id,
      data: data,
    };
    // Verify payload
    const errMsg = state_data.Input.verify(payload);
    if (errMsg) throw new Error(errMsg);
    // Create message
    const message = state_data.Input.create(payload);
    // Encode message
    const buffer = state_data.Input.encode(message).finish();
    return buffer;
  };
  //获取一个格式化的时间
  const getDateFromat = () => {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    const datatime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return datatime;
  };

  // 编码发送参数
  const encodeParams = (params: any, name: string) => {
    let item = state.root.lookupType(name)
    const errMsg = item.verify(params);
    if (errMsg) throw new Error(errMsg);
    const message = item.create(params);
    const buffer = item.encode(message).finish();
    return buffer;
  }

  // 获取快捷语列表
  const getShortcutlist = () => {
    const sendReq = state.root.lookupType('QuickPhrasesListReq');
    state.requestid++;
    const requestid = state.requestid;
    const type = 19; //
    const payload = {
      deviceid: state.deviceID,
      page: 1,
      pagesize: 200,
    };
    //编码消息体
    const errMsg2 = sendReq.verify(payload);
    if (errMsg2) throw new Error(errMsg2);
    const decodedata = sendReq.encode(
      sendReq.create(payload),
    ).finish();
    const encodedRequest = encodeInput(type, requestid, decodedata);
    IWebsocket.sendMessageHandler(encodedRequest);
  };
  // 接收快捷语列表
  const getShortcutMsg = (decodeobj1: any) => {
    if (decodeobj1.data) {
      const decodeobj00 = decodeContent(decodeobj1.data, 'QuickPhrasesListRsp');
      state_data.quickPhrasesList = decodeobj00.quickphrase;
      //   快捷语自动回复状态保存
      let arr = state_data.quickPhrasesList
      let bol = false
      let text = ''
      arr.map((item: any) => {
        if (item.isautorsp == 1) {
          bol = true
          text = item.content
        }
      })
      chat.setAutoreply(bol)
      chat.setAutoreplyText(text)
    }
  };
  // 自动回复逻辑
  // 自动回复的发送
  const sendMsg = (todeviceid: any) => {
    let testMsg = autoreplytext.value
    console.log('auto:testMsg', testMsg)
    if (testMsg) {
      const type = 6; // 给用户发消息
      state.requestid++;
      const requestid = state.requestid;
      const msginput = {
        data: testMsg
      };
      //编码文字形式消息内容
      let MessageTextContentItem = state.root.lookupType('MessageTextContent')
      const errMsg1 = MessageTextContentItem.verify(msginput);
      if (errMsg1) throw new Error(errMsg1);
      const msginputdata = MessageTextContentItem.encode(MessageTextContentItem.create(msginput)).finish();
      var datatime = getDateFromat()
      const msgcontent = {
        fromdeviceid: state.deviceID,
        todeviceid: todeviceid,
        sendtime: datatime,
        mtype: 1,//文字类型消息
        data: msginputdata,
      };
      state_data.sendObj[todeviceid] = new Date(datatime).getTime()
      //编码消息体
      let MessageInputeItem = state.root.lookupType('MessageInpute')
      const errMsg2 = MessageInputeItem.verify(msgcontent);
      if (errMsg2) throw new Error(errMsg2);
      const msgcontentdata = MessageInputeItem.encode(MessageInputeItem.create(msgcontent)).finish();
      const params = {
        type: type,
        requestid: requestid,
        data: msgcontentdata,
      };
      try {
        state.chatMessagesList && state.chatMessagesList.push({ date: datatime, requestid, role: 1, cstatus: 1, content: testMsg, name: '', type: 'MessageTextContent' })
      } catch (error) { }
      const encodedRequest = encodeParams(params, 'Input')
      IWebsocket.sendMessageHandler(encodedRequest);
    }
  }
  // 清理倒计时
  const clear = () => {
    state_data.timer && clearTimeout(state_data.timer);
    state_data.timer = null;
  };
  const getMinuteDifference = (timestamp1: any, timestamp2: any) => {
    var date1: any = new Date(timestamp1);
    var date2: any = new Date(timestamp2);
    var difference = Math.abs(date2 - date1); // 计算两个日期之间的差值（毫秒）
    return Math.floor(difference / 1000 / 60); // 转换为分钟
  }
  const startTimer = (decodeobj1: any) => {
    if (!autoreply.value) {
      clear()
      return
    }
    const decodeobj00 = decodeContent(decodeobj1.data, 'Message')
    if (!decodeobj00.cstatus) return
    const decodeobj2 = decodeContent(decodeobj00.content, 'MessageOutpute')

    state_data.autoSendObj[decodeobj2.fromdeviceid] = new Date(decodeobj2.sendtime).getTime()

    state_data.timer = setTimeout(() => {
      if (state_data.sendObj[decodeobj2.fromdeviceid] && state_data.autoSendObj[decodeobj2.fromdeviceid]) {
        const time1 = state_data.autoSendObj[decodeobj2.fromdeviceid]
        const time2 = state_data.sendObj[decodeobj2.fromdeviceid]
        const diffMinus = getMinuteDifference(time1, time2)  //几分钟内回复
        // sendMsg(decodeobj2.fromdeviceid) //同用户只回复一次
        if (diffMinus >= 3) {
        }
      } else {
        sendMsg(decodeobj2.fromdeviceid)
      }
    }, 1000 * 60 * 3);
  }
  onMounted(() => {
    state_data.sendObj = {}
    state_data.autoSendObj = {}
  })
  onUnmounted(() => {
    clear()
  })

  return {
    ...toRefs(state_data),
    getShortcutlist,
    getShortcutMsg,
    startTimer,
    getDateFromat,
    encodeParams,
    encodeInput,
    decodeContent,
  };
};
export default usechatHooks;
